package com.sec.android.app.myfiles.mockclass;

import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyInt;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.when;

/**
 * Created by jaebae on 2016-07-08.
 */
public class FileInputStreamMock {
    static int sOffset = 0;

    public static FileInputStream createMock(final File file) {
        FileInputStream inputStream = PowerMockito.mock(FileInputStream.class);
        sOffset = 0;

        try {
            doNothing().when(inputStream).close();
            when(inputStream.read(any(byte[].class), anyInt(), anyInt())).thenAnswer(new Answer<Integer>() {
                @Override
                public Integer answer(InvocationOnMock invocation) throws Throwable {
                    Object[] args = invocation.getArguments();

                    int byteCount = (int) args[2];
                    int ret = byteCount;
                    int tot = sOffset + byteCount;

                    int size = (int) file.length();

                    if (sOffset >= size) {
                        return -1;
                    }

                    if (tot > size) {
                        ret = size - sOffset;
                    }

                    sOffset += ret;

                    return ret;
                }
            });
        } catch (IOException e) {
            //DO NOTHING
        }

        return inputStream;
    }


}
